package com.jia.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.jia.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xiuyajia
 * @Date: 11/27/13 5:12 PM
 */
public class CallPrim extends Activity {

    private static final String UPPER_NUM = "upper";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        final EditText editText = (EditText) findViewById(R.id.editText);
        final CallThread callThread = new CallThread();
        callThread.start();

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editText.getText().toString();
                if (text.length() > 1) {
                    Message message = new Message();
                    message.what = 0x123;
                    Bundle bundle = new Bundle();
                    bundle.putInt(UPPER_NUM, Integer.valueOf(text));
                    message.setData(bundle);

                    callThread.handler.sendMessage(message);
                }

            }
        });


    }

    class CallThread extends Thread {

        public Handler handler;

        @Override
        public void run() {
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 0x123) {
                        int upper = msg.getData().getInt(UPPER_NUM);
                        List<Integer> nums = new ArrayList<Integer>();
                        boolean flag = true;
                        for (int i = 2; i < upper; i++) {
                            for (int j = 2; j < Math.sqrt(i); j++) {
                                if (i != 2 && i % j == 0) {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag == true) {
                                nums.add(i);
                            }
                            flag = true;

                        }
                        Toast.makeText(CallPrim.this, nums.toString(), Toast.LENGTH_LONG).show();
                    }
                }
            };
            Looper.loop();
        }
    }
}
